const express = require('express')
const router = express.Router();

module.exports = router

const db = require('../db')
const { formatData } = require('../utils')

// /POST /api/user/reg
router.post('/reg', async (req, res) => {
    const { username, password } = req.body;
    // 数据库操作
    let sql = `insert into userlist(username,password) values('${username}','${password}')`
    const data = await db.query(sql)
    res.send(formatData({data}))
})
    

router.get('/login', async (req, res) => {
    // req.query
    const {username,password} = req.query;
    let sql = `select * from userlist where username='${username}' and password='${password}'`
    const data = await db.query(sql)
    if(data.length>0){
        res.send(formatData.success(data[0]))
    }else{
        res.send(formatData.fail())
    }

})

// GET /api/user/list   获取用户列表
router.get('/list', async (req, res) => {
    const { page = 1, qty = 10 } = req.query
    let index = (page - 1) * qty
    // 数据库操作
    let sqls = `select * from userlist`
    const datas = await db.query(sqls)
    let sql = [`select * from userlist where 1=1`]
    sql.push(`ORDER BY reg_time desc limit ${index},${qty}`)
    sql = sql.join(' ')
    const data = await db.query(sql)
    res.send(formatData({
        ode: data.length>0 ? 200 : 400,
        data:{
            total:datas.length,
            result:data,
        }
    }))
})


//POST /api/user/add      添加用户
router.post('/add', async (req, res) => {

    const {username,password,phone,nickname} = req.body
    let sqls = [`insert into userlist (username,password,phone,nickname) values (`]
    let sql = []
    sql.push (`'${username}'`)
    sql.push (`'${password}'`)
    sql.push (`'${phone}'`)
    sql.push (`'${nickname}'`)
    sqls = sqls + sql.join()+` )` 

    const data = await db.query(sqls)
    res.send(formatData({data}));
})


//DELETE /api/user/list        删除单个用户
router.delete('/list', async(req, res)=>{
    const {id} = req.body
    let sql = `delete from userlist where id=${id}`
    const data = await db.query(sql)
    res.send(
        formatData({data})
    )
})
